package com.ydlclass.watch;

import com.ydlclass.NettyBootStrapInitializer;
import com.ydlclass.YrpcBootstrap;
import com.ydlclass.loadbnlancer.LoadBalancer;
import io.netty.channel.Channel;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.Map;

/**
 * @Author duWenJian
 * @Date 2023/11/7 14:35
 * @Version 1.0
 */
@Slf4j
public class UpAndDownWatcher implements Watcher {
    @Override
    public void process(WatchedEvent event) {

        if (event.getType() == Event.EventType.NodeChildrenChanged){
            String path = event.getPath();
            if (log.isDebugEnabled()){
                log.debug("检测到服务{}上下线将重新拉取服务列表",path);
            }

            // 重新拉取的服务列表
            String serviceName = getServiceName(path);
            List<InetSocketAddress> addresses = YrpcBootstrap
                    .getInstance()
                    .getRegistry()
                    .lookup(serviceName);
            // 动态上线
            for (InetSocketAddress address : addresses) {
                if (!YrpcBootstrap.CHANNEL_CACHE.containsKey(address)){
                    Channel channel = null;
                    try {
                         channel = NettyBootStrapInitializer
                                .getBootstrap()
                                .connect(address)
                                .sync()
                                .channel();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    YrpcBootstrap.CHANNEL_CACHE.put(address,channel);
                }
            }
            // 动态下线
            for (Map.Entry<InetSocketAddress,Channel> entry : YrpcBootstrap.CHANNEL_CACHE.entrySet()){
                if (!addresses.contains(entry.getKey())){
                    YrpcBootstrap.CHANNEL_CACHE.remove(entry.getKey());
                }
            }

            // 获取负载均衡器，进行重新的loadBalance
            LoadBalancer loadBalancer = YrpcBootstrap.LOAD_BALANCE_STRATEGY;
            loadBalancer.reLoadBalance(serviceName,addresses);


        }
    }

    private String getServiceName(String path) {
        String[] split = path.split("/");
        return split[split.length - 1];
    }
}
